#!/usr/bin/env python
#coding=utf-8
import sys, getpass, re, hashlib
from sqlalchemy.exc import OperationalError, IntegrityError
from models import db, User

def cmd():
    print u"""
        命令:
        setup -- 自动安装博客数据库
        createdb -- 安装数据库
        createadmin -- 创建超级管理帐户
        initial -- 初始化内容
    """
def createdb():
    '''create the database tables'''
    print u'正在安装数据库....'
    try:
        db.create_all()
        print u'数据库已安装完成'
        return True
    except:
        print u"数据库不存在，请先创建!"
        return False

def createadmin():
    '''create the superuser'''
    print u'正在创建超级管理帐户....'
    match_email = 0
    count = 1
    while not match_email or count:
        print u'请输入邮箱:'
        email = raw_input()
        match_email = re.match(r"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", email)
        if not match_email:
            print u'Email无法通过验证,请重新输入！'
        else:
            count = db.session.query(User).filter(User.email==email).count()
            if count:print u'Email已存在，请重新输入！'
    match_password = 0
    while not match_password:
        print u'请输入密码:'
        password = getpass.getpass()
        print u'确认密码:'
        password_comfirm = getpass.getpass()
        match_password = True if password==password_comfirm else False
        if not match_password:print u'密码输入不一致,请重试！'
    # md5
    md5 = hashlib.md5()
    md5.update(password)
    password_md5 = md5.hexdigest()
    # add user
    superuser = User(
        username = email.split('@')[0],
        email = email,
        password = password_md5,
        is_superuser = True
    )
    db.session.add(superuser)
    try:
        db.session.commit()
        print u"创建超级管理帐户成功!"
    except OperationalError, e:
        print u"没有用户表!"
    except IntegrityError, e:
        print u"email '%s' 已存在!" % email

def initial():
    '''initial the pypress'''
    print u'正在初始化内容....'


if __name__=='__main__':
    if len(sys.argv) != 2:
        cmd()
    else:
        if sys.argv[1] == 'createdb':
            createdb()
        elif sys.argv[1] == 'createadmin':
            createadmin()
        elif sys.argv[1] == 'initial':
            initial()
        elif sys.argv[1] == 'setup':
            step = createdb()
            if step:                
                createadmin()
                initial()
        else:
            cmd()
